package com.example.limit.rule;

import com.example.limit.entity.PurchaseRule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 购买规则定义 - 将数据库规则转换为Easy Rules规则
 */
public class PurchaseRuleDefinition {
    
    private final PurchaseRule dbRule;
    
    public PurchaseRuleDefinition(PurchaseRule dbRule) {
        this.dbRule = dbRule;
    }
    
    /**
     * 将数据库规则转换为Easy Rules规则
     */
    public Rule toEasyRule() {
        return new org.jeasy.rules.support.RuleBuilder()
            .name("Rule_" + dbRule.getId())
            .description(dbRule.getRuleName())
            .when(facts -> evaluateCondition(facts))
            .then(facts -> executeAction(facts))
            .build();
    }
    
    /**
     * 评估规则条件
     */
    private boolean evaluateCondition(Facts facts) {
        Map<String, Object> context = facts.get("context");
        Long userId = (Long) context.get("userId");
        String productId = (String) context.get("productId");
        String categoryId = (String) context.get("categoryId");
        Integer quantity = (Integer) context.get("quantity");
        LocalDateTime purchaseTime = (LocalDateTime) context.get("purchaseTime");
        
        // 检查规则是否在有效期内
        if (!isRuleActive(purchaseTime)) {
            return false;
        }
        
        // 检查目标值匹配
        if (!matchesTarget(context)) {
            return false;
        }
        
        // 根据规则类型评估条件
        switch (dbRule.getRuleType()) {
            case 1: return evaluateUserRule(userId, productId, quantity, context);
            case 2: return evaluateProductRule(userId, productId, quantity, context);
            case 3: return evaluateTimeRule(userId, productId, quantity, context);
            case 4: return evaluateOrderRule(userId, productId, quantity, context);
            default: return false;
        }
    }
    
    /**
     * 执行规则动作
     */
    private void executeAction(Facts facts) {
        // 规则通过，记录结果
        Map<String, Object> results = facts.get("results");
        if (results == null) {
            results = new HashMap<>();
            facts.put("results", results);
        }
        
        String ruleKey = "rule_" + dbRule.getId();
        results.put(ruleKey, true);
        results.put(ruleKey + "_name", dbRule.getRuleName());
    }
    
    private boolean isRuleActive(LocalDateTime purchaseTime) {
        return !purchaseTime.isBefore(dbRule.getStartTime()) && 
               !purchaseTime.isAfter(dbRule.getEndTime()) &&
               dbRule.getStatus() == 1;
    }
    
    private boolean matchesTarget(Map<String, Object> context) {
        if (dbRule.getTargetValue() == null || dbRule.getTargetValue().isEmpty()) {
            return true;
        }
        
        switch (dbRule.getRuleType()) {
            case 1: // 用户维度
                Long userId = (Long) context.get("userId");
                return dbRule.getTargetValue().equals(userId.toString());
            case 2: // 商品维度
                String productId = (String) context.get("productId");
                String categoryId = (String) context.get("categoryId");
                if (dbRule.getSubType() == 3) { // 单品
                    return dbRule.getTargetValue().equals(productId);
                } else if (dbRule.getSubType() == 4) { // 品类
                    return dbRule.getTargetValue().equals(categoryId);
                }
                break;
        }
        return true;
    }
    
    private boolean evaluateUserRule(Long userId, String productId, Integer quantity, Map<String, Object> context) {
        // 这里可以集成Redis计数服务
        // 简化实现：直接返回true，实际应该调用RedisCounterService
        return true;
    }
    
    private boolean evaluateProductRule(Long userId, String productId, Integer quantity, Map<String, Object> context) {
        // 简化实现
        return true;
    }
    
    private boolean evaluateTimeRule(Long userId, String productId, Integer quantity, Map<String, Object> context) {
        // 简化实现
        return true;
    }
    
    private boolean evaluateOrderRule(Long userId, String productId, Integer quantity, Map<String, Object> context) {
        // 简化实现
        return quantity <= dbRule.getLimitQuantity();
    }
    
    public PurchaseRule getDbRule() {
        return dbRule;
    }
}